package com.anmong.parser.service;

import com.anmong.parser.model.SubtitleEntry;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Service
public class SubtitleParserService {
    public String merge(String novelText, String srtText) {
        List<String> novelLines = Stream.of(novelText.split("\\R"))
                .map(String::trim)
                .filter(line -> !line.isEmpty())
                .collect(Collectors.toList());

        List<SubtitleEntry> srtEntries = parseSrt(srtText);

        StringBuilder resultSrt = new StringBuilder();
        int srtCursor = 0;
        int newSequence = 1;

        for (String novelLine : novelLines) {
            if (srtCursor >= srtEntries.size()) {
                System.err.println("警告：原始字幕已用尽，但小说原文还有剩余内容。");
                break;
            }

            String cleanNovelLine = cleanTextForComparison(novelLine);
            if (cleanNovelLine.isEmpty()) {
                continue;
            }

            StringBuilder combinedSrtText = new StringBuilder();
            String groupStartTime = srtEntries.get(srtCursor).getStartTime();
            String groupEndTime = srtEntries.get(srtCursor).getEndTime(); // 默认结束时间

            // --- 核心逻辑改进 ---
            // 使用更健壮的“前缀匹配”逻辑，而不是要求完全相等。
            while (srtCursor < srtEntries.size()) {
                SubtitleEntry nextSrtEntry = srtEntries.get(srtCursor);
                String cleanNextSrtText = cleanTextForComparison(nextSrtEntry.getText());

                // 检查：如果拼接下一条字幕后，结果仍然是小说行的“开头部分”，则接受它
                if (cleanNovelLine.startsWith(combinedSrtText.toString() + cleanNextSrtText)) {
                    // 接受这条字幕
                    combinedSrtText.append(cleanNextSrtText);
                    groupEndTime = nextSrtEntry.getEndTime(); // 更新结束时间
                    srtCursor++; // 移动光标，处理下一条字幕
                } else {
                    // 如果再加一条字幕就不匹配了，说明当前小说行对应的字幕组已经找完
                    break;
                }
            }

            // 如果因为某些原因（例如，第一条字幕就不匹配），导致一条字幕都没被消费，
            // 那么我们至少也要把这条字幕作为一个单独的行处理掉，防止无限循环。
            if (combinedSrtText.length() == 0 && srtCursor < srtEntries.size()) {
                System.err.println("警告：小说行与字幕无法匹配，将字幕作为单行处理。小说行: " + cleanNovelLine);
                groupEndTime = srtEntries.get(srtCursor).getEndTime();
                srtCursor++;
            }

            resultSrt.append(newSequence++).append("\n");
            resultSrt.append(groupStartTime).append(" --> ").append(groupEndTime).append("\n");
            resultSrt.append(novelLine).append("\n\n");
        }

        return resultSrt.toString();
    }

    private List<SubtitleEntry> parseSrt(String srtText) {
        List<SubtitleEntry> entries = new ArrayList<>();
        Pattern pattern = Pattern.compile("(\\d+)\\R([\\d:,]+)\\s-->\\s([\\d:,]+)\\R([\\s\\S]*?)(?=\\R{2,}|\\z)");
        Matcher matcher = pattern.matcher(srtText.trim() + "\n\n");

        while (matcher.find()) {
            try {
                int sequence = Integer.parseInt(matcher.group(1));
                String startTime = matcher.group(2).trim();
                String endTime = matcher.group(3).trim();
                String text = matcher.group(4).replaceAll("\\R", " ").trim();
                entries.add(new SubtitleEntry(sequence, startTime, endTime, text));
            } catch (Exception e) {
                System.err.println("解析SRT字幕块时出错: " + matcher.group(0));
            }
        }
        return entries;
    }

    private String cleanTextForComparison(String text) {
        // 移除所有空白字符、所有标点符号(包括中英文)和特殊符号
        return text.replaceAll("[\\s\\p{P}‘’“”`~!@#$%^&*()_\\-+=<>?:\"{}|,.\\/;'\\\\\\[\\]·~！@#￥%……&*（）——\\-—+={}|《》？：“”【】、；‘，。、]", "");
    }
}
